// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/dwio/dwrf/writer/ratio_tracker.h>
#include <pollux/common/exception/exception.h>

namespace kumo::pollux::dwrf {

RatioTracker::RatioTracker(float initialGuess)
    : workingAverage_{initialGuess} {}

float RatioTracker::getEstimatedRatio() const {
  return workingAverage_;
}

bool RatioTracker::isEmptyInput(size_t denominator, size_t numerator) {
  return denominator == 0;
}

void RatioTracker::takeSample(size_t denominator, size_t numerator) {
  // Discard empty input.
  if (isEmptyInput(denominator, numerator)) {
    return;
  }

  numeratorTotal_ += numerator;
  denominatorTotal_ += denominator;
  DWIO_ENSURE_GT(denominatorTotal_, 0);
  // Don't care about underflow.
  workingAverage_ = numeratorTotal_ * 1.0f / denominatorTotal_;
  ++sampleSize_;
}

size_t RatioTracker::getSampleSize() const {
  return sampleSize_;
}

CompressionRatioTracker::CompressionRatioTracker(float initialGuess)
    : RatioTracker{initialGuess} {}

bool CompressionRatioTracker::isEmptyInput(
    size_t denominator,
    size_t numerator) {
  return numerator == 0 || denominator == 0;
}

FlushOverheadRatioTracker::FlushOverheadRatioTracker(float initialGuess)
    : RatioTracker{initialGuess} {}

AverageRowSizeTracker::AverageRowSizeTracker(float initialGuess)
    : RatioTracker{initialGuess} {}

} // namespace kumo::pollux::dwrf
